package ink.charon.novel.utils;

import cn.hutool.core.lang.UUID;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.downloader.HttpClientDownloader;
import us.codecraft.webmagic.downloader.PhantomJSDownloader;
import us.codecraft.webmagic.selector.PlainText;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HttpUtil {
    public static Page getPage(String url, Site site){
        class NovelTask implements Task {
            Site site = null;
            @Override
            public String getUUID() {
                return UUID.fastUUID().toString();
            }
            @Override
            public Site getSite() {
                return site;
            }
            public void setSite(Site site) {
                this.site = site;
            }
        }
        NovelTask task = new NovelTask();
        task.setSite(site);
        return new HttpClientDownloader().download(new Request(url), task);
    }

    public static String getAjaxContent(String url) throws Exception {
        Runtime rt = Runtime.getRuntime();
        Process p = rt
                .exec("D:/software/spider/phantomjs.exe D:/software/spider/s.js "
                        + url);
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sbf = new StringBuffer();
        String tmp = "";
        while ((tmp = br.readLine()) != null) {
            sbf.append(tmp + "\n");
        }
        return sbf.toString();
    }

    public static Page download(Request request) {
        Page page = new Page();
        try {
            String url = request.getUrl();
            String html = getAjaxContent(url);
            page.setRawText(html);
            page.setUrl(new PlainText(url));
            page.setRequest(request);
            return page;
        } catch (Exception e) {
            System.out.println("download出错了!");
            return page;
        }
    }

    public static void main(String[] args) {
        System.out.println(new PhantomJSDownloader("D:/software/spider/phantomjs.exe", "D:/software/spider/s.js").download("http://book.zongheng.com/book/893499.html"));
        //System.out.println(download(new Request("http://book.zongheng.com/book/893499.html")).getHtml().get());
    }
}
